# coding: utf-8
import base64
from json import JSONDecodeError, loads, dumps

from django.db import models
from lib.common import BasicManager
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from project.settings_common import HELPPRIZE
from services.datamodel.student.models import Student
from services.datamodel.order.models import UserAddress
from services.datamodel.slider.models import mm_Slider
from django.db import transaction
from django.core.cache import cache
from lib.applet.applet_api import SpeechApplet


class ModelManagerSpeechActivity(BasicManager):
    def get_button_info(self):
        """wni：每次取小程序首页展示活动对应的按钮"""
        from services.datamodel.student.models import mm_Student
        res = self.filter(is_show=1).first()
        activity_info = {
            "theme": res.theme,
            "address": res.address,
            "live_activity_time": res.activity_time,
            "help_activity_time": cache.get('help_activity_time')
        }
        button_uv = loads(res.button_uv)
        ticket_uv = res.active_user.filter(lottery_ticket_no__isnull=False).count()
        ticket_code_uv = mm_Student.filter(source=11, channel=12).count()
        help_uv = mm_Student.filter(source=11, channel=11).count()
        auth_uv = mm_Student.filter(source=11, channel=13).count()
        evaluation_code_uv = mm_Student.filter(source=11, channel=14).count()
        return {
            "id": res.id,
            "activity_info": activity_info,
            "button_types": res.button_types,
            "button_content": res.button_content,
            "invite_help_uv": button_uv.get('invite_help', 0),
            "booking_uv": button_uv.get('booking', 0),
            "share_uv": button_uv.get('share', 0),
            "ticket_uv": ticket_uv,
            "ticket_code_uv": ticket_code_uv,
            "evaluation_code_uv": evaluation_code_uv,
            "help_uv": help_uv,
            "auth_uv": auth_uv
        }

    def get_index(self):
        """获取小程序首页"""
        activity_info = self.filter(is_show=1).values().first()
        banner = mm_Slider.filter(platform=4, is_show=1, types=1).values().order_by('-sort')
        special_column = mm_SpecialColumnVideo.filter(column_types=1, is_show=1).values(
            'id', 'name', 'thumb', 'video_url', 'video_types', 'like_num'
        ).order_by('-sort')
        return {
            "activity_info": activity_info,
            'help_activity_time': cache.get('help_activity_time'),
            'banner': list(banner),
            'special_column': list(special_column)
        }

    def add_button_uv(self, invite_help_uv=0, booking_uv=0, share_uv=0):
        """
        增加按钮uv
        @param invite_help_uv: 邀请助力
        @param booking_uv: 预约
        @param share_uv: 保存图片并分享
        @return:
        """
        active_obj = self.filter(is_show=1).first()
        button_uv = active_obj.button_uv
        try:
            button_uv = loads(button_uv)
        except JSONDecodeError:
            button_uv = {}
        invite_help = button_uv.get("invite_help")
        booking = button_uv.get("booking")
        share = button_uv.get("share")

        if not invite_help:
            button_uv["invite_help"] = 0
        if not booking:
            button_uv["booking"] = 0
        if not share:
            button_uv["share"] = 0

        button_uv["invite_help"] += int(invite_help_uv)
        button_uv["booking"] += int(booking_uv)
        button_uv["share"] += int(share_uv)

        active_obj.button_uv = dumps(button_uv)
        active_obj.save()


class ModelManagerSpecialColumn(BasicManager):
    def get_list(self, page, column_types, name=None, video_types=None, is_show=None):
        res = self.filter(column_types=column_types).values()
        if video_types:
            res = res.filter(video_types=video_types)
        if video_types == '4':
            res = res.order_by('-created_at').first()
            return res
        if column_types == 1:
            res = res.order_by('-id')
        if is_show:
            res = res.filter(is_show=is_show)
        if name:
            res = res.filter(name__contains=name)
        paginator = Paginator(res, 10)
        try:
            result_page = paginator.page(page)
        except PageNotAnInteger:
            result_page = paginator.page(1)
        except EmptyPage:
            return {'retlist': [], 'curpageidx': page,
                    'hasnext': False, 'hasprevious': False}

        return {'retlist': list(result_page), 'curpageidx': page,
                'hasnext': result_page.has_next(), 'hasprevious': result_page.has_previous(),
                'total_page': paginator.num_pages}

    def get_user_story(self):
        """小程序获取用户故事"""
        user_story = self.filter(column_types=2, is_show=1, video_types=3).values(
            'id', 'name', 'thumb', 'video_url', 'avatar', 'detail'
        )
        top_video = self.filter(column_types=2, is_show=1, video_types=4). \
            values('video_url').order_by('-created_at').first()
        return {
            "user_story": list(user_story),
            "top_video": top_video
        }

    def do_like(self, id, is_like):
        """
        点赞
        @param id:
        @param is_like: 0 or 1
        @return:
        """
        video_obj = self.filter(id=id).first()
        if is_like == '0':
            video_obj.like_num -= 1
        elif is_like == '1':
            video_obj.like_num += 1
        video_obj.save()
        return {"like_num": video_obj.like_num}


class ModelManagerActiveUser(BasicManager):

    def generate_lottery_ticket_no(self, id):
        """
        生成抽奖券
        @param id:active_user_id
        @return:
        """
        active_user = self.get(id=id)
        no = active_user.lottery_ticket_no
        if not no:
            from random import randint
            no = randint(10, 99) * 1000000 + int(id)
            active_user.lottery_ticket_no = no
            active_user.save()
        return {"lottery_ticket_no": no}

    def create_active_user(self, s_id):
        """
        生成活动用户
        @param s_id: student_id
        @return:
        """
        activit_obj = mm_SpeechActivity.filter(is_show=1).first()
        if activit_obj:
            obj, _ = mm_SpeechActiveUser.get_or_create(
                student_id=s_id,
                speech_antivity=activit_obj
            )
            return {"active_user_id": obj.id}
        return {}

    def get_helped_info(self, active_user_id):
        """
        获取被助力信息
        @param active_user_id:
        @return:
        """
        active_user = self.get(id=active_user_id)
        avatar_list = self.filter(helped_student=active_user).values('student__avatar')
        help_num = avatar_list.count()

        one_level = mm_WinningList.get_winning_info(active_user_id, 1)
        two_level = mm_WinningList.get_winning_info(active_user_id, 2)
        three_level = mm_WinningList.get_winning_info(active_user_id, 3)
        four_level = mm_WinningList.get_winning_info(active_user_id, 4)

        return {
            "avatar": [avatar['student__avatar'] for avatar in avatar_list],
            "help_num": help_num,
            "need_num": HELPPRIZE.FOUR_LEVEL_NUM - help_num,
            "winning_info": {
                "one_level": one_level,
                "two_level": two_level,
                "three_level": three_level,
                "four_level": four_level,
            }
        }

    @staticmethod
    def send_message(helped_user_id, helped_num):
        """
        发送领奖通知
        @param helped_user_id: 被助力人
        @param helped_num: 助力人数
        @return:
        """
        helped_user = mm_SpeechActiveUser.get(id=helped_user_id)
        applet_openid = helped_user.student.applet_openid
        access_token = cache.get('applet_access_token')
        applet_obj = SpeechApplet()

        if not access_token:
            res = applet_obj.get_access_token(SpeechApplet.APPID, SpeechApplet.SECRET)
            access_token = res.get('access_token')
            expires_in = res.get('expires_in')
            cache.set('applet_access_token', access_token, expires_in - 60)
        p1 = '好友助力得千元红包'
        p2 = f'已经有 {helped_num} 位好友给你助力了'
        p3 = '每个阶段都有不同的奖品可以领，去看看吧！'
        p4 = '好友助力通知'
        t_data = applet_obj.generate_t_data(p1, p2, p3, p4)
        applet_obj.send_template(access_token, applet_openid, SpeechApplet.TEAMPLATE_ID, t_data, page='pages/tabBar/first/first')

    def help(self, active_user_id, helped_user_id):
        """
        助力
        @param active_user_id:助力人
        @param helped_user_id:被助力人
        @return:
        """
        import random
        active_user = self.get(id=active_user_id)
        if active_user.helped_student:
            return {"retcode": 1, "message": "已助力，不可重复助力！"}
        if active_user_id == helped_user_id:
            return {"retcode": 1, "message": "无法给自己助力哦！"}
        active_user.helped_student_id = helped_user_id
        active_user.save()
        # 按比例选取助力金额
        proportion = {0.66: 0.7, 1.88: 0.25, 8.88: 0.05}
        amount = random.choices(list(proportion.keys()), weights=list(proportion.values()))[0]
        cache.set(f"{active_user_id}_amount", amount, 6 * 30 * 86400)

        helped_num = mm_SpeechActiveUser.filter(helped_student_id=helped_user_id).count()
        if helped_num == HELPPRIZE.ONE_LEVEL_NUM:
            mm_WinningList.create(active_user_id=helped_user_id, level=1)
            self.send_message(helped_user_id, helped_num)

        elif helped_num == HELPPRIZE.TWO_LEVEL_NUM:
            mm_WinningList.create(active_user_id=helped_user_id, level=2)
            self.send_message(helped_user_id, helped_num)

        elif helped_num == HELPPRIZE.THREE_LEVEL_NUM:
            mm_WinningList.create(active_user_id=helped_user_id, level=3)
            self.send_message(helped_user_id, helped_num)

        elif helped_num == HELPPRIZE.FOUR_LEVEL_NUM:
            mm_WinningList.create(active_user_id=helped_user_id, level=4)
            self.send_message(helped_user_id, helped_num)

        return {"retcode": 0, "message": "助力成功", "data": {"amount": amount}}

    def get_help_info(self, helped_user_id, s_id):
        """
        获取助力消息
        @param helped_user_id:被助力人活动id
        @param s_id:助力人
        @return:
        """
        activity_obj = mm_SpeechActivity.filter(is_show=1).first()
        active_user = self.filter(student_id=s_id, speech_antivity=activity_obj).first()
        if active_user and active_user.id == int(helped_user_id):
            return {"retcode": 4, "message": "无法给自己助力哦"}

        if not active_user or not active_user.helped_student:
            return {"retcode": 1, "message": "未助力"}

        elif active_user.helped_student_id == int(helped_user_id):
            amount = cache.get(f'{active_user.id}_amount', 0)
            return {"retcode": 0, "message": "帮好友助力成功", "data": {"amount": amount}}

        else:
            return {"retcode": 3, "message": "你已经给另一位好友助力过，不能重复助力哦！"}

    def generate_code(self, mobile, page, channel, rgb="{}"):
        """
        生成小程序码
        @param mobile:
        @param page:
        @return:
        """
        applet_obj = SpeechApplet()
        access_token = cache.get('applet_access_token')
        if not access_token:
            res = applet_obj.get_access_token(SpeechApplet.APPID, SpeechApplet.SECRET)
            access_token = res.get('access_token')
            expires_in = res.get('expires_in')
            cache.set('applet_access_token', access_token, expires_in - 60)

        res = applet_obj.generate_QR_code(access_token, f"mobile={mobile},c={channel}", page, loads(rgb))
        try:
            res = res.json()
            errmsg = res.get('errmsg')
            return {"retcode": 1, "message": "生成失败", "error": errmsg, "access_token": access_token}

        except JSONDecodeError:
            # binary -> base64 —> str
            code_data = "data:image/png;base64," + base64.b64encode(res.content).decode()
            return {"retcode": 0, "message": "OK", "data": code_data}

    def get_ticket_list(self, page, export=None):
        res = self.filter(lottery_ticket_no__isnull=False).values(
            "student__avatar", "student__nick_name", "lottery_ticket_no"
        )
        if export:
            from io import BytesIO
            from django.http import HttpResponse
            import xlwt
            ws = xlwt.Workbook(encoding="UTF-8")
            w = ws.add_sheet(u'数据')
            w.write(0, 0, u'用户昵称')
            w.write(0, 1, u'用户头像')
            w.write(0, 2, u'抽奖码')
            excel_row = 1
            for obj in res:
                w.write(excel_row, 0, obj['student__nick_name'])
                w.write(excel_row, 1, obj['student__avatar'])
                w.write(excel_row, 2, obj['lottery_ticket_no'])
                excel_row += 1
            sio = BytesIO()
            ws.save(sio)
            sio.seek(0)
            response = HttpResponse(sio.getvalue(), content_type='application/vnd.ms-excel')
            response['Content-Disposition'] = 'attachment; filename=stu_info.xls'
            response.write(sio.getvalue())
            return response
        paginator = Paginator(res, 15)
        try:
            result_page = paginator.page(page)
        except PageNotAnInteger:
            result_page = paginator.page(1)
        except EmptyPage:
            return {'retlist': [], 'curpageidx': page,
                    'hasnext': False, 'hasprevious': False}

        return {'retlist': list(result_page), 'curpageidx': page,
                'hasnext': result_page.has_next(), 'hasprevious': result_page.has_previous(),
                'total_page': paginator.num_pages}

    def get_avtivety_info_for_id(self, sid):
        """
        根据id获取跨年活动信息
        @param sid: studentid
        @return:
        """
        active_user = self.filter(student_id=sid, speech_antivity__is_show=1).values().first()
        if active_user:
            return {
                "amount": cache.get(f'{active_user.get("id")}_amount', 0),
            }
        return {}

    def batch_send_msg(self, page):
        """
        批量发送订阅消息
        @param page: 跳转页面
        @return:
        """
        applet_obj = SpeechApplet()
        applet_res = applet_obj.get_access_token(SpeechApplet.APPID, SpeechApplet.SECRET)
        access_token = applet_res.get('access_token')
        expires_in = applet_res.get('expires_in')
        cache.set('applet_access_token', access_token, expires_in - 60)
        p1 = "nihao"
        p2 = "nihao"
        p3 = "nihao"
        p4 = "nihao"
        t_data = applet_obj.generate_t_data(p1, p2, p3, p4)
        from concurrent.futures.thread import ThreadPoolExecutor
        # 多线程发送
        pool = ThreadPoolExecutor(100)
        res = self.values("student__applet_openid")
        for i in res:
            pool.submit(applet_obj.send_template, *(access_token, i['student__applet_openid'], SpeechApplet.TEAMPLATE_ID, t_data, page))

        pool.shutdown(wait=True)

    def get_phone(self, encryptedData, iv, applet_openid):
        """
        获取手机号
        @param encryptedData:
        @param iv:
        @param applet_openid:
        @return:
        """
        applet_openid = applet_openid
        session_key = cache.get(f'{applet_openid}_session_key')
        if not session_key:
            return {"retcode": 3, "message": "获取失败", "error": "session_key过期"}

        applet_obj = SpeechApplet()
        try:
            res = applet_obj.decrypt_get_phone(session_key, iv, encryptedData)
            phone = res.get('phoneNumber')
            return {"retcode": 0, "message": "获取成功", "data": {'phone': phone}}

        except Exception as e:
            return {"retcode": 3, "message": "获取失败", "error": str(e),
                    'data': {
                        "session_key": session_key,
                        "encryptedData": encryptedData,
                        "iv": iv
                    }}


class ModelManagerUserComment(BasicManager):
    def get_comment_list(self, page, nick_name=None, mobile=None, export=None, is_ban=None):
        res = self.values('id', 'active_user__student__nick_name', 'active_user__student__mobile',
                          'active_user__student__avatar', 'created_at', 'content',
                          'active_user__is_ban', 'active_user__id').order_by('-created_at')
        if is_ban:
            res = res.filter(active_user__is_ban=is_ban)
        if nick_name:
            res = res.filter(active_user__student__nick_name=nick_name)
        if mobile:
            res = res.filter(active_user__student__mobile=mobile)
        if export:
            from io import BytesIO
            from django.http import HttpResponse
            import xlwt
            ws = xlwt.Workbook(encoding="UTF-8")
            w = ws.add_sheet(u'数据')
            w.write(0, 0, u'用户昵称')
            w.write(0, 1, u'用户头像')
            w.write(0, 2, u'用户手机号')
            w.write(0, 3, u'留言时间')
            w.write(0, 4, u'留言内容')
            excel_row = 1
            for obj in res:
                w.write(excel_row, 0, obj['active_user__student__nick_name'])
                w.write(excel_row, 1, obj['active_user__student__avatar'])
                w.write(excel_row, 2, obj['active_user__student__mobile'])
                w.write(excel_row, 3, obj['created_at'])
                w.write(excel_row, 4, obj['content'])
                excel_row += 1
            sio = BytesIO()
            ws.save(sio)
            sio.seek(0)
            response = HttpResponse(sio.getvalue(), content_type='application/vnd.ms-excel')
            response['Content-Disposition'] = 'attachment; filename=stu_info.xls'
            response.write(sio.getvalue())
            return response
        paginator = Paginator(res, 15)
        try:
            result_page = paginator.page(page)
        except PageNotAnInteger:
            result_page = paginator.page(1)
        except EmptyPage:
            return {'retlist': [], 'curpageidx': page,
                    'hasnext': False, 'hasprevious': False}

        return {'retlist': list(result_page), 'curpageidx': page,
                'hasnext': result_page.has_next(), 'hasprevious': result_page.has_previous(),
                'total_page': paginator.num_pages}

    def get_comments(self):
        activit_obj = mm_SpeechActivity.filter(is_show=1).first()
        res = self.filter(active_user__speech_antivity=activit_obj).values(
            'active_user__student__avatar', 'content'
        ).order_by('-created_at')

        return list(res)


class ModelManagerWinningList(BasicManager):
    def get_winning_list(self, page, level, nick_name=None, mobile=None, export=None):
        res = self.filter(level=level).values(
            'active_user__student__nick_name', 'active_user__student__id', 'address__name', 'address__phone',
            'active_user__student__mobile', 'active_user__student__avatar', 'created_at', 'address__address',
            'address__provincename', 'address__cityname', 'address__districtname'
        ).order_by('-created_at')
        if nick_name:
            res = res.filter(active_user__student__nick_name=nick_name)
        if mobile:
            res = res.filter(active_user__student__mobile=mobile)
        if export:
            from io import BytesIO
            from django.http import HttpResponse
            import xlwt
            ws = xlwt.Workbook(encoding="UTF-8")
            w = ws.add_sheet(u'数据')
            w.write(0, 0, u'用户ID')
            w.write(0, 1, u'用户昵称')
            w.write(0, 2, u'用户手机号')
            w.write(0, 3, u'头像')
            w.write(0, 4, u'完成时间')
            w.write(0, 5, u'用户收货姓名')
            w.write(0, 6, u'用户收货手机号')
            w.write(0, 7, u'用户收货地址')
            w.write(0, 8, u'用户收货省')
            w.write(0, 9, u'用户收货市')
            w.write(0, 10, u'用户收货区')
            excel_row = 1
            for obj in res:
                w.write(excel_row, 0, obj['active_user__student__id'])
                w.write(excel_row, 1, obj['active_user__student__nick_name'])
                w.write(excel_row, 2, obj['active_user__student__mobile'])
                w.write(excel_row, 3, obj['active_user__student__avatar'])
                w.write(excel_row, 4, obj['created_at'])
                w.write(excel_row, 5, obj['address__name'])
                w.write(excel_row, 6, obj['address__phone'])
                w.write(excel_row, 7, obj['address__address'])
                w.write(excel_row, 8, obj['address__provincename'])
                w.write(excel_row, 9, obj['address__cityname'])
                w.write(excel_row, 10, obj['address__districtname'])
                excel_row += 1
            sio = BytesIO()
            ws.save(sio)
            sio.seek(0)
            response = HttpResponse(sio.getvalue(), content_type='application/vnd.ms-excel')
            response['Content-Disposition'] = 'attachment; filename=stu_info.xls'
            response.write(sio.getvalue())
            return response
        paginator = Paginator(res, 50)
        try:
            result_page = paginator.page(page)
        except PageNotAnInteger:
            result_page = paginator.page(1)
        except EmptyPage:
            return {'retlist': [], 'curpageidx': page,
                    'hasnext': False, 'hasprevious': False}

        return {'retlist': list(result_page), 'curpageidx': page,
                'hasnext': result_page.has_next(), 'hasprevious': result_page.has_previous(),
                'total_page': paginator.num_pages}

    def get_winning_info(self, active_user_id, level):
        """
        获取单阶领奖信息
        @param active_user_id:
        @param level:
        @return: 0：不可领取，1：可领取，2：已领取
        """
        res = self.filter(active_user_id=active_user_id, level=level).first()
        if not res:
            return 0
        return 1


    def receive_award(self, level, active_user_id, name=None, phone=None, address=None, provincename=None, cityname=None,
                      districtname=None, user_id=None):
        """
        领取奖品
        @param level:
        @param active_user_id:
        @param name:
        @param phone:
        @param address:
        @param provincename:
        @param cityname:
        @param districtname:
        @param user_id:
        @return:
        """
        try:
            with transaction.atomic():
                obj = self.filter(active_user_id=active_user_id, level=level).first()
                if not obj:
                    return {"retcode": 1, "message": "未完成助力任务"}

                if all([name, phone, address, provincename, cityname, districtname, user_id]):
                    from services.datamodel.order.models import mm_Address

                    address_obj, _ = mm_Address.get_or_create(
                        name=name, phone=phone, address=address, provincename=provincename,
                        cityname=cityname, districtname=districtname, student_id=user_id
                    )
                    obj.address = address_obj
                    obj.save()

                return {"retcode": 0, "message": "领奖成功"}
        except:
            return {"retcode": 1, "message": "出现错误"}


class SpeechActivity(models.Model):
    """
    该表后台无法添加，必须先数据库手动添加活动，一次只能有一个is_show=1
    关联包括：预约按钮，活动用户，用户留言
    """
    theme = models.CharField("活动主题", max_length=30, null=False, blank=False)
    activity_time = models.DateTimeField("活动时间", max_length=6, null=False, blank=False)
    address = models.CharField("活动地址", max_length=150, null=False, blank=False)
    is_show = models.PositiveSmallIntegerField("是否展示为当前活动", default=0, null=True, blank=True)  # 0否 1是
    button_types = models.PositiveSmallIntegerField('预约按钮跳转类型', default=1)  # 1：公众号链接推文，2：视频号视频
    button_content = models.CharField("按钮跳转内容", max_length=200, null=True, blank=True)
    # {"invite_help": 0, "booking": 0, "share": 0}  invite_help:邀请助力, booking:预约, share:分享小程序码按钮
    button_uv = models.CharField("按钮uv", max_length=100, default='{}')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    objects = ModelManagerSpeechActivity()

    class Meta:
        verbose_name = '演讲活动表'
        verbose_name_plural = verbose_name
        db_table = 'momself_speech_activity'


class SpecialColumnVideo(models.Model):
    name = models.CharField('名称', max_length=100, null=True, blank=True)
    thumb = models.CharField("封面", max_length=200, null=True, blank=True)
    video_url = models.CharField("视频", max_length=200, null=True, blank=True)
    column_types = models.PositiveSmallIntegerField('栏目类型', default=0)  # 1：首页专栏，2：用户故事
    video_types = models.PositiveSmallIntegerField('视频类型', default=0)  # 1：专栏图片， 2：专栏视频，3：用户视频， 4：熄灯视频
    is_show = models.PositiveSmallIntegerField("是否上架", default=1)  # 0：不上架，1：上架
    detail = models.TextField("专栏详情", null=True, blank=True)
    sort = models.IntegerField("排序", default=0)
    like_num = models.IntegerField("点赞数", default=0)
    avatar = models.CharField("故事头像", max_length=150, null=True, blank=True)
    created_at = models.DateTimeField("添加时间", auto_now_add=True)
    updated_at = models.DateTimeField("修改时间", auto_now=True)

    objects = ModelManagerSpecialColumn()

    class Meta:
        verbose_name = '首页专栏视频'
        verbose_name_plural = verbose_name
        db_table = "momself_special_column_video"


class SpeechActiveUser(models.Model):
    """微信授权后将自动寻找当前演讲活动创建用户，作为参加活动的标志"""
    student = models.ForeignKey(Student, verbose_name='活动用户')
    helped_student = models.ForeignKey('self', null=True, blank=True, verbose_name='被助力用户')
    speech_antivity = models.ForeignKey(SpeechActivity, related_name='active_user')
    lottery_ticket_no = models.IntegerField("抽奖券编码", unique=True, null=True, blank=True)
    is_ban = models.PositiveSmallIntegerField('是否禁言', default=0)  # 0: 否, 1: 是


    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    objects = ModelManagerActiveUser()

    class Meta:
        verbose_name = '演讲活动用户表'
        verbose_name_plural = verbose_name
        db_table = 'momself_speech_active_user'
        unique_together = [("student", "speech_antivity")]


class UserComment(models.Model):
    active_user = models.ForeignKey(SpeechActiveUser)
    content = models.TextField('留言内容', null=False, blank=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    objects = ModelManagerUserComment()

    class Meta:
        verbose_name = '留言表'
        verbose_name_plural = verbose_name
        db_table = 'momself_user_comment'


class WinningList(models.Model):
    active_user = models.ForeignKey(SpeechActiveUser)
    address = models.ForeignKey(UserAddress, null=True, blank=True)
    level = models.PositiveSmallIntegerField('中奖阶级', default=0)  # 0:默认，1：1阶，2：2阶，3：3阶，4：4阶
    # is_receive = models.PositiveSmallIntegerField('是否领取', default=0)  # 0：否 1：是
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    objects = ModelManagerWinningList()

    class Meta:
        verbose_name = '获奖名单表'
        verbose_name_plural = verbose_name
        db_table = 'momself_winning_list'
        unique_together = [("active_user", "level")]


mm_SpecialColumnVideo = SpecialColumnVideo.objects
mm_SpeechActivity = SpeechActivity.objects
mm_SpeechActiveUser = SpeechActiveUser.objects
mm_UserComment = UserComment.objects
mm_WinningList = WinningList.objects
